const koa = require("koa");
const bodyParser = require("koa-bodyparser");
const Router = require("@koa/router");
const cors = require("koa2-cors");
const staticFiles = require('koa-static');
const path = require('path');
const fs = require('fs');
const formidable = require("formidable");
const mkdirs = require('./utils/upload.js')
const app = new koa();
const router = new Router();
app.use(bodyParser());
app.use(cors());

const staticPath = './static';

app.use(staticFiles(path.join( __dirname, staticPath)));



router.post("/uploadimg", async (ctx, next) => {
  const form = formidable({ multiples: true, uploadDir: __dirname });

  await new Promise((resolve, reject) => {
    form.parse(ctx.req, (err, fields, files) => {
      if (err) {
        reject(err);
        return;
      }

      ctx.set("Content-Type", "application/json");
      ctx.status = 200;
      let uploadDir = 'static/';
      let filename = Date.now() + files.file.name

      mkdirs('public/upload', function() {
        fs.renameSync(files.file.path, uploadDir + filename); //重命名

      })
      const url = ctx.request.header.host + '/' + filename
      ctx.response.body = {
        status: '0',
        url: url
      }
      resolve();
    });
    
  });
  await next();
});

app.use(router.routes());

app.listen(8888);
